#include <iostream>
#include <thread>
#include <pthread.h>
#include <unistd.h>
using namespace std;

// C++也可以使用线程
/*
void my_fun()
{
    cout<<"我是一个线程执行流"<<endl;
}
int main()
{
    thread tobj(my_fun);
    cout<<"我是主线程"<<endl;

    tobj.join();//等待

    return 0;
}
*/

// tid实际就是共享区里线程集中的起始地址（在pthread_create时才给值）
/*
int main()
{
    pthread_t tid;
    cout<<"tid = "<<tid<<endl;
    pthread_create(&tid,nullptr,nullptr,nullptr);
    cout<<"tid = "<<tid<<endl;

    return 0;
}
*/

//int g_val = 0; // 全局变量是所有线程共享
__thread int g_val=0;//__thread修饰的全局变量，在线程的局部存储(每一个线程单独一份)
//__thread只能修饰内置类型
void *thread_fun(void *fun)
{
    while (1)
    {
        cout << "one_thread g_val = " << g_val << " ,&g_val = " << &g_val << endl;
        g_val++;
        sleep(1);
    }
}
void *thread_f(void *fun)
{
    while (1)
    {
        cout << "two_thread g_val = " << g_val << " ,&g_val = " << &g_val << endl;
        g_val++;
        sleep(1);
    }
}
int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, thread_fun, nullptr);
    pthread_create(&tid, nullptr, thread_f, nullptr);
    while (1)
    {
        cout << "main_thread g_val = " << g_val << " ,&g_val = " << &g_val << endl;
        sleep(1);
    }

    return 0;
}
